package com.why.search.service.impl;

import com.alibaba.fastjson.JSON;

import com.why.search.config.GuliESConfig;
import com.why.search.constant.EsConstant;
import com.why.search.service.ProductSaveService;
import com.why.to.SkuEsModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Created: with IntelliJ IDEA.
 * @author: 夏沫止水
 * @createTime: 2020-06-06 16:54
 **/

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient esRestClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

//        保存到es中
//        1.建立对应的索引


//        批量保存数据   BulkRequest bulkRequest, RequestOptions options  构造一个批量的保存请求

        BulkRequest request = new BulkRequest();
        for (SkuEsModel esModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);

            String jsonString = JSON.toJSONString(esModel);

            indexRequest.source(jsonString, XContentType.JSON);
            indexRequest.id(esModel.getSkuId().toString());
            request.add(indexRequest);
        }


        BulkResponse bulk = esRestClient.bulk(request, GuliESConfig.COMMON_OPTIONS);

        //TODO 如果批量错误  需要做处理
        boolean hasFailures = bulk.hasFailures();

        List<String> collect = Arrays.asList(bulk.getItems()).stream().map(item -> {
            return item.getId();
        }).collect(Collectors.toList());

        log.info("商品上架完成：{}",collect);

        return hasFailures;
    }
}
